package utils

import (
	"fmt"
	"gitee.com/ymofen/deadlock/internal"
	"os"
	"sync/atomic"
	"time"
)

var (
	filePrefix string
	baseDir    string
	fileSN     atomic.Int32
	exeName    string
)

func init() {
	exeName = os.Args[0] //获取程序名称
	exeName = internal.ExtractFileNameWithOutPathAndExt(exeName)
	filePrefix = fmt.Sprintf("%s-%d-deadlock", exeName, os.Getpid())
}

func SetDeadlockWriteFilePath(dir string) error {
	baseDir = dir
	if len(baseDir) > 0 {
		if baseDir[len(baseDir)-1] == '/' || baseDir[len(baseDir)-1] == '\\' {
		} else {
			baseDir = fmt.Sprintf("%s%s", baseDir, internal.PathSeparator)
		}
	}

	err := os.MkdirAll(baseDir, 0777)
	if err != nil && !os.IsExist(err) {
		return err
	}
	filePrefix = fmt.Sprintf("%s%s-%d-deadlock", baseDir, exeName, os.Getpid())
	return nil
}

func WriteDeadLockToFile(data []byte) error {
	now := time.Now() //获取当前时间
	datestr := now.Format("20060102")
	nowstrEx := now.Format("2006-01-02 15:04:05.999")
	//设定时间格式
	fname := fmt.Sprintf("%s-%s-%d.log", filePrefix, datestr, fileSN.Add(1))

	f, err := os.OpenFile(fname, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = f.WriteString(fmt.Sprintf("%s dead lock\r\n", nowstrEx)) //输出panic信息
	if err != nil {
		return err
	}
	f.WriteString("---------------------------------------------\r\n")
	_, err = f.Write(data)
	return err
}
